package cn.com.utt.unms.service.impl;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.TimeZone;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.alibaba.fastjson.JSON;

import cn.com.utt.common.util.LocaleMessageSourceUtil;
import cn.com.utt.common.util.Tips;
import cn.com.utt.common.vo.RestResult;
import cn.com.utt.common.vo.SearchParameter;
import cn.com.utt.common.vo.TableInput;
import cn.com.utt.common.vo.TableOutput;
import cn.com.utt.unms.mapper.EventLogMapper;
import cn.com.utt.unms.mapper.NetworkMapper;
import cn.com.utt.unms.pojo.Device;
import cn.com.utt.unms.pojo.EventLog;
import cn.com.utt.unms.pojo.Network;
import cn.com.utt.unms.service.DeviceService;
import cn.com.utt.unms.service.EventLogService;
import cn.com.utt.unms.vo.EventLogInfo;

@Service("eventLogService")
public class EventLogServiceImpl implements EventLogService{
	
	@Autowired
	private EventLogMapper eventLogMapper;
	
	@Autowired
	private DeviceService deviceService;
	
	@Autowired
	private NetworkMapper networkMapper;
	
	@Autowired
    private LocaleMessageSourceUtil messageSourceUtil;
	
	public String formatDate(Object stamp){
		DateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");   
		return sdf.format(stamp);
	}

	@Override
	public RestResult queryEventLogByType(long networkId) {
		//查询当前局点下所有的设备
		List<Device> devices=deviceService.queryDevicesByNetworkIds(new ArrayList<Long>(){{add(networkId);}});
		RestResult result=null;
		if(devices.size()>0){
			String []sn=new String[devices.size()];
			for (int i = 0; i < devices.size(); i++) {
				sn[i]=devices.get(i).getSn();
			}
			long dayTime = System.currentTimeMillis();
			long zero=dayTime/(1000*3600*24)*(1000*3600*24)-TimeZone.getDefault().getRawOffset();
			List<Map<String, Object>> list=eventLogMapper.queryEventLogByTypeAndSn(sn, formatDate(zero));
			if(list.size()>0){
				result=new RestResult();
				for (int i = 0; i < list.size(); i++) {
					if(list.get(i).get("type").toString().equals("1")){
						result.put("告警",list.get(i).get("count"));
					}else if(list.get(i).get("type").toString().equals("2")){
						result.put("通知", list.get(i).get("count"));
					}else{
						result.put("消息", list.get(i).get("count"));
					}
				}
			}
			if(result==null){
				result=new RestResult();
				result.put("告警",0);
				result.put("通知", 0);
				result.put("消息", 0);
			}
			List<EventLog> eventLogs=eventLogMapper.queryEventLogs(sn,formatDate(zero));
			List<EventLogInfo> eventLogInfos=new ArrayList<>();
			if(eventLogs.size()>0){
				for (EventLog eventLog : eventLogs) {
					EventLogInfo eventLogInfo=new EventLogInfo();
					if(eventLog.getType()==1){
						eventLogInfo.setType(messageSourceUtil.getMessage(Tips.Alert));
					}else if(eventLog.getType()==2){
						eventLogInfo.setType(messageSourceUtil.getMessage(Tips.Msg));
					}else{
						eventLogInfo.setType(messageSourceUtil.getMessage(Tips.Msg));
					}
					Device device=deviceService.queryDeviceBySn(eventLog.getSn());
					eventLogInfo.convert(eventLog);
					eventLogInfo.setDeviceName((device.getName()==null||device.getName()==""||device.getName().length()==0)?device.getMac():device.getName());
					eventLogInfos.add(eventLogInfo);
				}
				if(eventLogInfos!=null&&eventLogInfos.size()>0){
					System.out.println("eventLogInfos: "+JSON.toJSON(eventLogInfos));
					result.put("eventLogs", JSON.toJSON(eventLogInfos));
				}
			}else{
				result.put("eventLogs", null);
			}
			
		}else{
			result=new RestResult();
			result.put("告警",0);
			result.put("通知", 0);
			result.put("消息", 0);
			result.put("eventLogs", null);
		}
		
		return result;
	}

	@Override
	public TableOutput<EventLogInfo> queryByCondition(TableInput input, long userGroupId,long userId) {
		Map<String, Object> conditions = new HashMap<>();
		List<Long> networkIds = new ArrayList<>();
		//筛选数据
		if(input.getSearch()!=null && input.getSearch().size() > 0){
			Iterator<SearchParameter> iterator = input.getSearch().iterator();
			while (iterator.hasNext()) {
				SearchParameter search = iterator.next();
				if ("network_id".equals(search.getColumn())) {
					// 如果有以参数中的network来查询设备，如果没有则以组下的所有局点来查询
					networkIds.add(Long.parseLong(search.getValue()));
					iterator.remove();
					break;
				}
			}
		}
		conditions.put("searchs", input.getSearch());
		if (input.getOrder() != null) {
			conditions.put("orderColumn", input.getOrder().getColumn());
			conditions.put("orderDirection", input.getOrder().getDir());
		}else{
			conditions.put("orderColumn", "stamp");
			conditions.put("orderDirection", "desc");
		}
		conditions.put("start", input.getStart());
		conditions.put("rows", input.getRows());
		List<Device> devices=null;
		//筛选数据--，若有选择了局点，按局点查询数据
		if(networkIds.size()>0){
			devices=deviceService.queryDevicesByNetworkIds(networkIds);
		}else{
			//当前用户所拥有的分组下的所有设备
			devices = deviceService.queryChildrenDevicesByGroupId(userGroupId);
		}
		List<String> sns = new ArrayList<>();
		for (int i = 0; i < devices.size(); i++) {
			sns.add(devices.get(i).getSn());
		}
		List<EventLogInfo> infos = new ArrayList<>();
		int total=0;
		if(sns.size()>0){
			conditions.put("sns", sns);
			System.out.println(JSON.toJSON(conditions));
			total=eventLogMapper.countByCondition(conditions);
			List<EventLog> eventLogs=eventLogMapper.queryByCondition(conditions);
			if(eventLogs != null){
				for (EventLog eventLog : eventLogs) {
					EventLogInfo info = new EventLogInfo();
					if(eventLog.getType()==1){
						info.setType(messageSourceUtil.getMessage(Tips.Alert));
					}else if(eventLog.getType()==2){
						info.setType(messageSourceUtil.getMessage(Tips.Msg));
					}else{
						info.setType(messageSourceUtil.getMessage(Tips.Msg));
					}
					//添加设备名称--2018/4/3
					Device device=deviceService.queryDeviceBySn(eventLog.getSn());
					//添加局点--2018/5/30
					Network network = networkMapper.queryById(device.getNetworkId());
					String deviceName=(device.getName()==null||device.getName()==""||device.getName().length()==0)?device.getMac():device.getName();
					info.convert(eventLog);
					info.setDeviceName(deviceName);
					info.setNerworkId(network.getId());
					info.setGroup(network.getName());
					infos.add(info);
				}
			}
		}
		TableOutput<EventLogInfo> output = new TableOutput<>();
		output.setTotal(total);
		output.setRows(input.getRows());
		output.setStart(input.getStart());
		output.setList(infos);
		return output;
	}
	

}
